package cn.valo.basic.interceptor;

import cn.valo.basic.jwt.JwtUtils;
import cn.valo.basic.jwt.LoginResult;
import cn.valo.basic.jwt.Payload;
import cn.valo.basic.jwt.RsaUtils;
import cn.valo.system.annotation.PreAuthorize;
import cn.valo.system.mapper.PermissionMapper;
import cn.valo.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("U-TOKEN");
//        if (StringUtils.hasLength(token)) {
//            Object loginTmp = redisTemplate.opsForValue().get(token);
//            if(loginTmp!=null){
//                Logininfo logininfo = (Logininfo) loginTmp;
//                if(logininfo.getType() == 0){//0为员工进入权限判断
//                    //。得到当前请求的资源 url
//                    HandlerMethod method = (HandlerMethod) handler;
//                    PreAuthorize annotation = method.getMethodAnnotation(PreAuthorize.class);
//                    if(annotation != null){
//                        String currentSn = annotation.value();//本次请求的sn
//                        //。查询出当前登录人拥有的权限的资源 permissions
//                        List<String> permissions = permissionMapper.loadPermissionsByLogininfoId(logininfo.getId());
//                        //。判断permissions是否包含url
//                        if(!permissions.contains(currentSn)){//不包含进入
//                            PrintWriter writer = response.getWriter();
//                            writer.write("{\"success\":false,\"message\":\"noPermission\"}");
//                            writer.flush();
//                            writer.close();
//                            return false;//阻止放行
//                        }
//                    }
//                }
//                //不包含
//                redisTemplate.opsForValue().set(token,loginTmp,1, TimeUnit.HOURS);
//                return true;
        if(StringUtils.hasLength(token)){
            //获取公钥
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
            //使用公钥解密token
            Payload<LoginResult> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginResult.class);
            //获取登录人信息
            LoginResult loginResult = payload.getUserInfo();
            if(loginResult!=null){//不等于null说明已经登录
                //判断登录人的type
                if(loginResult.getLogininfo().getType()==0){//为0则判断权限
                    //。得到当前请求的资源 url
                    HandlerMethod method = (HandlerMethod) handler;
                    PreAuthorize annotation = method.getMethodAnnotation(PreAuthorize.class);
                    if(annotation != null){
                        String currentSn = annotation.value();//本次请求的sn
                        //。查询出当前登录人拥有的权限的资源 permissions
                        //List<String> permissions = permissionMapper.loadPermissionsByLogininfoId(logininfo.getId());
                        //。判断permissions是否包含url
                        if(!loginResult.getPermissions().contains(currentSn)){
                            //。 不包含。。提示权限不足，请联系管理员
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"message\":\"noPermission\"}");
                            writer.flush();
                            writer.close();
                            return false;//阻止放行
                        }
                }

            }//登录成功且有权限
                return true;
            }
        }
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        return false;//阻止放行
    }


}